import { useState, useRef, useEffect } from 'react'

import store from '../../store'
import http from '../../request'

function torem(num) {
  return num / 16 + 'rem'
}
function IndexBar(props) {
  const [city,setCity] = useState(null)
  const [index, setIndex] = useState([])
  let [len, setLen] = useState([])
  let doc = useRef(null)
  const [position, setPosition] = useState('A')

  useEffect(() => {
    if(city) return

    getCity()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  
  useEffect(() => {
    let length = []
    for (let i = 0; i < index.length; i++) {
      if (i === 0) { length[i] = (city[index[i]].length + 1) * 31; } else {
        length[i] = length[i - 1] + (city[index[i]].length + 1) * 31;
      }
    }
    setLen(length)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [index])

  return (
    <div className='u-flex-top'>
      <div style={{ flex: 1, overflow: 'scroll' }} ref={doc} onScroll={scroll}>
        {index.map(i => <div key={i}><div id={i} className={position === i ? 'u-sticky' : ''} 
        style={position === i ? { lineHeight: torem(30), backgroundColor: 'rgb(247,248,250)', color: "red"} : { lineHeight: torem(30), backgroundColor: 'rgb(247,248,250)', borderBottom: '1px solid #d9d9d9' }}>{i}</div>
        {city[i].map(t => <div onClick={(t.regionName === '北京') || (t.regionName === '上海') || 
        (t.regionName === '广州') ? () => change(t.regionName) : ()=>{}} key={t.id} style={{ lineHeight: torem(30), borderBottom: '1px solid #d9d9d9' }}>{t.regionName}</div>)}</div>)}
      </div>
      <div className='u-fixed' style={{ width: torem(14), right: 0, top: torem(180), }}>
        {index.map(i => <div key={i} onClick={() =>jumpClick(i)} style={position === i ? {color: 'red'} : {}}>{i}</div>)}
      </div>
    </div>
  )
  // 获取城市数据
  function getCity() {
    http('/city').then(res => {
      if(res.data.data.returnCode === '0') {
        setCity(res.data.data.returnValue)
        setIndex(Object.keys(res.data.data.returnValue))
      }
    }).catch(err => console.log(err))
  }
  // 监听滚动，判断当前位置
  function scroll() {
      const top = doc.current.scrollTop
      setPosition(index[len.findIndex(i => i > top)])
  }
  // 点击锚点跳转
  function jumpClick(i) {
    document.querySelector(`#${i}`).scrollIntoView(true)
  }
  // 改变城市
  function change(city) {
    store.dispatch({type: 'changeCity', data: city})
    props.open(!1)
    props.get && props.get()
  }
}

export default IndexBar